<?php

namespace app\api\service;

use app\api\model\ProductModel;
use app\api\model\ProductPlanCostModel;
use app\api\model\ProductPlanNoRateModel;
use app\api\model\ProductPlatModel;
use app\api\model\WorkCategoryModel;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

class ProductPlanService extends Api
{
    protected static $instance;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 添加、编辑产品方案
     */
    public function changeProductPlan($params)
    {
        Db::startTrans();
        try{
            if ($params['planType'] == 3)
            {
                $Validate = new Validate([
                    'product_id' => 'require',
                    'plan' => 'require',
                    'work_cate' => 'require',
                ], [
                    'product_id' => '产品标识无效',
                    'plan' => '产品方案未配置',
                    'work_cate' => '缺少职业类别'
                ]);
                if (!$Validate->check($params))
                {
                    $this->error($Validate->getError());
                }
                ProductPlatModel::getInstance()->delete([
                    'product_id' => ['eq', $params['product_id']]
                ]);
                ProductPlanNoRateModel::getInstance()->delete([
                    'product_id' => ['eq', $params['product_id']]
                ]);

                foreach ($params['plan'] as $k => $v)
                {
                    $schemeCode = empty($v['scheme_code']) ? datetime(time(), 'ymd').rand(10,99) : $v['scheme_code'];
                    foreach ($v['month'] as $kk => $vv)
                    {
                        $rateData[] = [
                            'product_id' => $params['product_id'],
                            'plan_id' => 0,
                            'proCode' => $schemeCode,
                            'month' => $vv['month'],
                            'money' => $vv['money'],
                            'c_time' => datetime(time(),  'Y-m-d H:i:s'),
                            'work_cate' => json_encode($params['work_cate'])
                        ];
                    }
                    $saveData[] = [
                        'product_id' => $params['product_id'],
                        'death_quota' => $v['death_quota'],
                        'medical_quota' => $v['medical_quota'],
                        'loss_work_cost' => $v['loss_work_cost'],
                        'hospital_allowance' => $v['hospital_allowance'],
                        'legal_fees' => $v['legal_fees'],
                        'scheme_code' => $schemeCode,
                        'disability_ratio' => json_encode([]),
                        'is_expand_24_hours' => 0,
                        'plan_type' => !empty($params['planType']) ? $params['planType'] : 1,
                        'insure_ratio_24_hours' => 1,
                        'c_time' => datetime(time(), 'Y-m-d H:i:s')
                    ];
                }
                ProductPlatModel::getInstance()->insertAll($saveData);
                $planInfo = ProductPlatModel::getInstance()->column([
                    'product_id' => ['eq', $params['product_id']]
                ], 'id', 'scheme_code');
                foreach ($rateData as $k => &$v)
                {
                    $v['plan_id'] = $planInfo[$v['proCode']];
                    unset($v['proCode']);
                }
                ProductPlanNoRateModel::getInstance()->insertAll($rateData);
            }else{
                $checkData = [
                    'product_id' => 'require',
                    'is_expand_24_hours' => 'require',
                    'disability_ratio' => 'require',
                    'plan' => 'require',
                ];
                $checkMsg = [
                    'product_id' => '产品标识无效',
                    'is_expand_24_hours' => '是否扩展24小时必填',
                    'disability_ratio' => '伤残比例必填',
                    'plan' => '产品方案必填'
                ];
                /*if (!empty($params['is_expand_24_hours']))
                {
                    $checkData['insure_ratio_24_hours'] = 'require';
                    $checkMsg['insure_ratio_24_hours'] = '扩展24小时投保比例必填';
                }*/
                $Validate = new Validate($checkData, $checkMsg);
                if (!$Validate->check($params))
                {
                    $this->error($Validate->getError());
                }
                $Validate = new Validate([
                    'death_quota' => 'require',
                    'medical_quota' => 'require',
                    'loss_work_cost' => 'require',
                    'hospital_allowance' => 'require',
                    'legal_fees' => 'require',
                    'scheme_code' => 'require',
                    'work_cate' => 'require',
                ], [
                    'death_quota' => '死亡、伤残限额必填',
                    'medical_quota' => '医疗责任限额必填',
                    'loss_work_cost' => '误工费必填',
                    'hospital_allowance' => '住院津贴必填',
                    'legal_fees' => '法律费用必填',
                    'scheme_code' => '方案编码必填',
                    'work_cate' => '职业类别费用必填',
                ]);
                if (!empty($params['plan'][0]))
                {
                    if (!$Validate->check($params['plan'][0]))
                    {
                        $this->error($Validate->getError());
                    }
                }
                $Validate = new Validate([
                    'is_five_percent' => 'require',
                    'five_ratio' => 'require',
                    'is_one_percent' => 'require',
                    'one_ratio' => 'require',
                    'is_ten_percent' => 'require',
                    'ten_ratio' => 'require',
                ], [
                    'is_five_percent' => '伤残比例5%设置必填',
                    'five_ratio' => '伤残比例5%投保费率必填',
                    'is_one_percent' => '伤残比例1%设置必填',
                    'one_ratio' => '伤残比例1%投保费率必填',
                    'is_ten_percent' => '伤残比例10%设置必填',
                    'ten_ratio' => '伤残比例10%投保费率必填',
                ]);
                if (!$Validate->check($params['disability_ratio']))
                {
                    $this->error($Validate->getError());
                }

                ProductPlatModel::getInstance()->delete([
                    'product_id' => ['eq', $params['product_id']]
                ]);
                ProductPlanCostModel::getInstance()->delete([
                    'product_id' => ['eq', $params['product_id']]
                ]);
                foreach ($params['plan'] as $k => $v)
                {
                    $schemeCode = empty($v['scheme_code']) ? datetime(time(), 'ymd').rand(10,99) : $v['scheme_code'];
                    foreach ($v['work_cate'] as $kk => $vv)
                    {
                        $costData[] = [
                            'product_id' => $params['product_id'],//int(10) DEFAULT NULL COMMENT '产品id',
                            'plan_id' => 0,//int(10) DEFAULT NULL COMMENT '方案id',
                            'work_cate' => json_encode($vv['ids']),//varchar(128) DEFAULT NULL COMMENT '职业类别  json',
                            'money' => $params['planType'] == 2 ? 0 : $vv['money'],//int(11) DEFAULT '0' COMMENT '年保费   乘10000 存储',
                            'c_time' => datetime(time(), 'Y-m-d H:i:s'),//datetime DEFAULT NULL,
                            'proCode' => $schemeCode,
                            'extend_money' => $params['planType'] == 2 ? json_encode([
                                'one_money' => !empty($vv['one_money']) ? $vv['one_money'] : 0,
                                'five_money' => !empty($vv['five_money']) ? $vv['five_money'] : 0,
                                'ten_money' => !empty($vv['ten_money']) ? $vv['ten_money'] : 0,
                            ]) : json_encode([]),
                            'code' => isset($vv['workCode']) ? $vv['workCode'] : $schemeCode
                        ];
                    }
                    $saveData[] = [
                        'product_id' => $params['product_id'],
                        'death_quota' => $v['death_quota'],
                        'medical_quota' => $v['medical_quota'],
                        'loss_work_cost' => $v['loss_work_cost'],
                        'hospital_allowance' => $v['hospital_allowance'],
                        'legal_fees' => $v['legal_fees'],
                        'scheme_code' => $schemeCode,
                        'disability_ratio' => json_encode($params['disability_ratio']),
                        'is_expand_24_hours' => $params['is_expand_24_hours'],
                        'plan_type' => !empty($params['planType']) ? $params['planType'] : 1,
                        'insure_ratio_24_hours' => !empty($params['is_expand_24_hours']) ? ($params['planType'] == 2 ? ( $params['is_insure_ratio_24_hours'] == 2 ? $v['insure_ratio_24_hours'] : ( isset($params['insure_ratio_24_hours']) ? $params['insure_ratio_24_hours'] : 1 ) ) : $params['insure_ratio_24_hours']) : 1,
                        'is_insure_ratio_24_hours' => isset($params['is_insure_ratio_24_hours']) ? $params['is_insure_ratio_24_hours'] : 1,
                        'c_time' => datetime(time(), 'Y-m-d H:i:s')
                    ];
                }
                ProductPlatModel::getInstance()->insertAll($saveData);
                $planInfo = ProductPlatModel::getInstance()->column([
                    'product_id' => ['eq', $params['product_id']]
                ], 'id', 'scheme_code');
                foreach ($costData as $k => &$v)
                {
                    $v['plan_id'] = $planInfo[$v['proCode']];
                    unset($v['proCode']);
                }
                ProductPlanCostModel::getInstance()->insertAll($costData);
            }
            LogService::getInstance()->writeSysLog([
                'operation' => '/api/productPlan/changeProductPlan',
                'title' => '设置产品方案',
                'content' => $params,
            ]);
            Db::commit();
            return true;
        }catch (Exception $e)
        {
            Db::rollback();
            $this->error('服务器错误');
        }
    }

    /**
     * 获取方案信息
     */
    public function getProductPlan($params)
    {
        $Validate = new Validate([
            'product_id' => 'require'
        ], [
            'product_id' => '产品标识无效'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $plan = ProductPlatModel::getInstance()->select([
            'product_id' => ['eq', $params['product_id']]
        ]);
        $ids = array_column($plan, 'id');
        $cost = ProductPlanCostModel::getInstance()->select([
            'product_id' => ['eq', $params['product_id']],
            'plan_id' => ['in', $ids]
        ]);
        $noRate = ProductPlanNoRateModel::getInstance()->select([
            'product_id' => ['eq', $params['product_id']],
            'plan_id' => ['in', $ids]
        ], 'plan_id, month, money, work_cate');
        $result = [];
        $result['product_id'] = $params['product_id'];
        $result['company_id'] = ProductModel::getInstance()->productValue([
            'id' => ['eq', $params['product_id']]
        ], 'company');
        $result['lib_id'] = 0;
        foreach ($plan as $k => $v)
        {
            $result['is_expand_24_hours'] = $v['is_expand_24_hours'];
            $result['insure_ratio_24_hours'] = $v['insure_ratio_24_hours'];
            $result['is_insure_ratio_24_hours'] = $v['is_insure_ratio_24_hours'];
            $result['disability_ratio'] = json_decode($v['disability_ratio'], true);
            $result['planType'] = $v['plan_type'];
            $workCate = [];
            foreach ($cost as $kk => $vv)
            {
                if ($v['id'] == $vv['plan_id'])
                {
                    $result['lib_id'] = WorkCategoryModel::getInstance()->find(json_decode($vv['work_cate'], true)[0])['lib_id'];
                    $extendMoney = json_decode($vv['extend_money'], true);
                    $woArr = [
                        'ids' => json_decode($vv['work_cate'], true),
                        'money' => $vv['money'],
                        'workCode' => $vv['code'],
                    ];
                    if (!empty($extendMoney))
                    {
                        foreach ($extendMoney as $kkk => $vvv)
                        {
                            $woArr[$kkk] = $vvv;
                        }
                    }
                    $workCate[] = $woArr;
                }
            }
            $rateData = $work_cate = [];
            foreach ($noRate as $kk => $vv)
            {
                if ($v['id'] == $vv['plan_id'])
                {
                    $rateData[] = [
                        'month' => $vv['month'],
                        'money' => $vv['money'],
                    ];
                    $work_cate = json_decode($vv['work_cate']);
                }
            }
            $result['work_cate'] = $work_cate;
            $result['plan'][] = [
                'death_quota' => $v['death_quota'],
                'medical_quota' => $v['medical_quota'],
                'loss_work_cost' => $v['loss_work_cost'],
                'hospital_allowance' => $v['hospital_allowance'],
                'legal_fees' => $v['legal_fees'],
                'scheme_code' => $v['scheme_code'],
                'work_cate' => $workCate,
                'month' => $rateData,
                'insure_ratio_24_hours' => $v['insure_ratio_24_hours']
            ];
        }
        return $result;
    }
}